/**
 *  Copyright [2022] [https://www.xiaonuo.vip]
 *	Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *	1.请不要删除和修改根目录下的LICENSE文件。
 *	2.请不要删除和修改Snowy源码头部的版权声明。
 *	3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 *	4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 *	5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 *	6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
/*
 * @Descripttion: 工具集
 * @version: 1.1
 * @LastEditors: yubaoshan
 * @LastEditTime: 2022年4月19日10:58:41
 */
const tool = {}

// localStorage
tool.data = {
	set(table, settings) {
		const _set = JSON.stringify(settings)
		return localStorage.setItem(table, _set)
	},
	get(table) {
		let data = localStorage.getItem(table)
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data
	},
	remove(table) {
		return localStorage.removeItem(table)
	},

	clear() {
		// 增加保留项
		const PHONE_METHOD = tool.data.get('PHONE_METHOD')
		const CB_SWITCH_TYPE = tool.data.get('CB_SWITCH_TYPE')
		localStorage.clear()
		PHONE_METHOD && tool.data.set('PHONE_METHOD', PHONE_METHOD)
		CB_SWITCH_TYPE && tool.data.set('CB_SWITCH_TYPE', CB_SWITCH_TYPE)
		// return localStorage.clear()
	}
}

// sessionStorage
tool.session = {
	set(table, settings) {
		const _set = JSON.stringify(settings)
		return sessionStorage.setItem(table, _set)
	},
	get(table) {
		let data = sessionStorage.getItem(table)
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data
	},
	remove(table) {
		return sessionStorage.removeItem(table)
	},
	clear() {
		return sessionStorage.clear()
	}
}

// 千分符
tool.groupSeparator = (num) => {
	num = `${num}`
	if (!num.includes('.')) num += '.'

	return num
		.replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => {
			return `${$1},`
		})
		.replace(/\.$/, '')
}

// 获取所有字典数组
tool.dictDataAll = () => {
	return tool.data.get('DICT_TYPE_TREE_DATA')
}

// 字典翻译方法，界面插槽使用方法 {{ $TOOL.dictType('sex', record.sex) }}
tool.dictTypeData = (dictValue, value, emptyDictVal = '无此字典项', emptyDict = '无此字典') => {
	const dictTypeTree = tool.dictDataAll()
	if (!dictTypeTree) {
		return '需重新登录'
	}
	const tree = dictTypeTree.find((item) => item.dictValue === dictValue)
	if (!tree) {
		return emptyDict
	}
	const children = tree.children
	const dict = children.find((item) => item.dictValue === value)
	return dict ? dict.dictLabel : emptyDictVal
}

// 获取某个code下字典的列表，多用于字典下拉框
tool.dictTypeList = (dictValue) => {
	const dictTypeTree = tool.dictDataAll()
	if (!dictTypeTree) {
		return []
	}
	const tree = dictTypeTree.find((item) => item.dictValue === dictValue)
	if (tree && tree.children) {
		return tree.children
	}
	return []
}

// 获取某个code下字典的列表，基于dictTypeList 改进，保留老的，逐步替换
tool.dictList = (dictValue) => {
	const dictTypeTree = tool.dictDataAll()
	if (!dictTypeTree) {
		return []
	}
	const tree = dictTypeTree.find((item) => item.dictValue === dictValue)
	if (tree) {
		return tree.children.map((item) => {
			return {
				value: item['dictValue'],
				label: item['name']
			}
		})
	}
	return []
}

// 树形翻译 需要指定最顶级的 parentValue  和当级的value
tool.translateTree = (parentValue, value) => {
	const tree = tool.dictDataAll().find((item) => item.dictValue === parentValue)
	const targetNode = findNodeByValue(tree, value)
	return targetNode ? targetNode.dictLabel : ''
}
const findNodeByValue = (node, value) => {
	if (node.dictValue === value) {
		return node
	}
	if (node.children) {
		for (let i = 0; i < node.children.length; i++) {
			const result = findNodeByValue(node.children[i], value)
			if (result) {
				return result
			}
		}
	}
	return null
}

// 生成UUID
tool.snowyUuid = () => {
	let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
		let r = (Math.random() * 16) | 0,
			v = c === 'x' ? r : (r & 0x3) | 0x8
		return v.toString(16)
	})
	// 首字符转换成字母
	return 'xn' + uuid.slice(2)
}

// 获取组织下人员
tool.getAllBottomPersonIds = (nodes) => {
	return nodes.reduce((total, item) => {
		const { children } = item.pos ? item : item.props || {}
		if (children && children.length) {
			total.push(...tool.getAllBottomPersonIds(children))
		} else {
			const { props, id } = item.pos ? item.node : item
			const eId = props ? props.id : id
			if (eId.includes('_')) {
				total.push(eId.split('_')[1])
			}
		}
		return total
	}, [])
}

// 手机号中间4位脱敏
tool.desensitizePhone = (phone, num = 4) => phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')

/**
 * 遍历树形结构
 * @param root
 * @param callback
 */
tool.traverseDepartmentTreeDFS = (root, callback) => {
	if (!root) return

	function dfs(node, parentNode) {
		callback(node, parentNode) // 访问当前节点
		node.children && node.children.forEach((item) => dfs(item, node)) // 递归遍历子节点
	}

	if (Array.isArray(root)) {
		root.forEach((item) => dfs(item))
	} else {
		dfs(root) // 从根节点开始深度优先搜索
	}
}

/**
 * 判断两个数组是否有交集
 */
tool.hasIntersection = (arr1, arr2) => {
	for (let i = 0; i < arr1.length; i++) {
		if (arr2.indexOf(arr1[i]) !== -1) {
			return true
		}
	}
	return false
}

/**
 * 限制点击（单击或双击）
 */
tool.timerData = {
	timer: null,
	time: 0
}
tool.limitClick = (callback, interval = 400) => {
	const time = new Date().getTime()

	if (tool.timerData.time && time - tool.timerData.time <= interval) {
		clearTimeout(tool.timerData.timer)
		return
	}
	tool.timerData.time = time
	tool.timerData.timer = setTimeout(() => {
		clearTimeout(tool.timerData.timer)
		callback && callback()
	}, interval)
}

// 深拷贝对象
tool.deepClone = (obj) => {
	const _toString = Object.prototype.toString

	// null, undefined, non-object, function
	if (!obj || typeof obj !== 'object') {
		return obj
	}

	// DOM Node
	if (obj.nodeType && 'cloneNode' in obj) {
		return obj.cloneNode(true)
	}

	// Date
	if (_toString.call(obj) === '[object Date]') {
		return new Date(obj.getTime())
	}

	// RegExp
	if (_toString.call(obj) === '[object RegExp]') {
		const flags = []
		if (obj.global) {
			flags.push('g')
		}
		if (obj.multiline) {
			flags.push('m')
		}
		if (obj.ignoreCase) {
			flags.push('i')
		}

		return new RegExp(obj.source, flags.join(''))
	}

	const result = Array.isArray(obj) ? [] : obj.constructor ? new obj.constructor() : {}

	for (const key in obj) {
		result[key] = tool.deepClone(obj[key])
	}

	return result
}

/* 递归处理tree，当children为空或空数组的，将children置为null */
tool.analyticTree = (tree) => {
	for (const t of tree) {
		if (!t.children || t.children.length <= 0) {
			t.children = null
		} else {
			t.children = tool.analyticTree(t.children)
		}
		t.label = t.name
	}

	return tree
}

/**
 * 解析组织架构数据，当children为空或空数组的，将children置为null
 * @param {Array[Object]} departmentTree 组织架构数据
 * @returns {Array[Object]}
 */
tool.analyticDepartmentTree = (departmentTree) => {
	for (const department of departmentTree) {
		if (!department.children || department.children.length <= 0) {
			department.children = null
		} else {
			department.children = tool.analyticDepartmentTree(department.children)
		}
	}

	return departmentTree
}

/* 加法  */
tool.accAdd = (arg1, arg2) => {
	let r1, r2
	try {
		r1 = arg1.toString().split('.')[1].length
	} catch (e) {
		r1 = 0
	}
	try {
		r2 = arg2.toString().split('.')[1].length
	} catch (e) {
		r2 = 0
	}
	const m = Math.pow(10, Math.max(r1, r2))
	return (arg1 * m + arg2 * m) / m
}
/* 减法  */
tool.accSubtr = (arg1, arg2) => {
	let r1, r2
	try {
		r1 = arg1.toString().split('.')[1].length
	} catch (e) {
		r1 = 0
	}
	try {
		r2 = arg2.toString().split('.')[1].length
	} catch (e) {
		r2 = 0
	}
	const m = Math.pow(10, Math.max(r1, r2))
	// 动态控制精度长度
	const n = r1 >= r2 ? r1 : r2
	return ((arg1 * m - arg2 * m) / m).toFixed(n)
}

/* 复制 */
tool.copyText = (copytext) => {
	return new Promise((resolve) => {
		if (navigator.clipboard) {
			// console.log('navigator.clipboard', navigator.clipboard.writeText);
			navigator.clipboard.writeText(copytext).then(() => {
				// this.$Message.success('复制成功');
				resolve()
			})
		} else {
			const save = function (e) {
				e.clipboardData.setData('text/plain', copytext)
				e.preventDefault() // 阻止默认行为
			}
			document.addEventListener('copy', save) // 添加一个copy事件
			const bool = document.execCommand('copy') // 执行copy方法
			// console.log('execCommand', bool);
			bool && resolve()
		}
	})
}

export default tool
